# coding="utf-8"
import json
import time
from datetime import datetime, timedelta
from threading import Thread

import requests


class Maotai(object):
    def __init__(self):
        self.session = requests.session()
        self.skuId = "100012043978"  # 茅台
        self.buy_time = "2024-11-13 11:59:59.500"
        self.run_time = 5  # 分钟
        # 打开 https://order.jd.com/center/list.action
        # F12 控制台输入 console.log(_JdJrTdRiskFpInfo, _JdEid)
        self.cookie = "__jdu=17168938620941289400292; shshshfpa=54015608-3744-05be-359e-ebace78fffa7-1716893862; shshshfpx=54015608-3744-05be-359e-ebace78fffa7-1716893862; b_webp=1; b_avif=1; mba_muid=17168938620941289400292; user-key=af3b4b9f-6b3b-4a35-a121-0ea5687db257; unpl=JF8EAR5nNSttUEkAVhgLHxUTHF5TWwhcSUQDO2ANV10PG1YFGwJMEBl7XlVdWBRLFh9sZBRUWFNKVA4ZBysSFXtdVV9cAUkeC25iNWRfXUxUAR0AEhcZQlpVWF0LJWRkbzIGURVYLlJ_GGxpfBBNXlxaWw9NFgFtbwEUXV5IBAYcUhIWQEJaFFhVC0MnAG9XBGRdXktTDBMAEhUTSlVRXl4BQxICbmQNV21Ze1QNHzIbExFKWVxcVAhOFgpfZwRVXVBNVAEYC3UXEEpcXFhYD0kRbW1nBFVdW0lXAR4yGxYXQlhWX1UASicCX2UEVV1cQlIGHQcrUH6c8N-JzomTu5u7x4kEDQgGVAMbBRIaEkJaV19VDUsUCmdiBFVeUEhkBCsB; TrackID=1f9Q5YU-qV7muc7-HqxIOWVE2HHGddE--DmIIhjAutZckNIEvjtuSExMLpOxS6BZP7SoXWFAx4L6u3NVOwyUOHSAbIELNWpm2KUObJfQ_QF8; thor=904FAEF65F997FC341A725A226939D6BFADE812B1DEF3B63EF3E2032B87C9A7F6F24E427E47C66C16394D92082B07CDE23B12E9C64D333E205513D3A5803D14C0931CC1049861A17CD894B2D23EE2041A748577E986EB3EE649A203B0D7319ABFF8E183767A4EB6BB71F22944FD360B690C2F1CF8CAD7632CBA956212720C7BBF13141DC52102594E9001011FF8FE35883E2097BF8A174492EBDB7AA33F6B14A; light_key=AASBKE7rOxgWQziEhC_QY6yautvaaqZvLwuOuhDJn4_COj42zeRd_bGjae-9TcirOU8VNIVE; pinId=QdNOdKWoykwbwuvnqu_ISQ; pin=jd_PquWOLOJHXdq; unick=jd_rb1t31xxo49knh; _tp=r92W93QM5M%2FuMjnP%2Bax4Bg%3D%3D; _pst=jd_PquWOLOJHXdq; autoOpenApp_downCloseDate_auto=1730356982777_1800000; b_dw=1903; b_dh=936; b_dpr=1; __jdv=95931165%7Clianmeng__2__kong%7Ct_1001050073_3189521%7Cjingfen%7C66a65aa2cef547d3a24d154a762b85b5%7C1730358594947; flash=3__BDfq1_ABphRxxHIMA10p7DW_EohKDDFHbY49Ezokvj901sLZizSa2JinWQxHDoBqGSxCsgWqYQBGzNYKX8JipTbLK-qK_VXetF2bdAD03E8nwaJhJtqIFadIdEcTJz7sj04qlF3sRvQkHk9W8EhKiKet-Tym3EVluSVjVosXw5S0ml7OBVX; 3AB9D23F7A4B3CSS=jdd033VM6TBS57CEX4IXYY4XBEB6RZS6FAACKPRVL5K3DFL5W3YPFN2WXLYWCWFK54X6HBGC4INUEKIIFQ4G4UFLQNIM56YAAAAMS4FUMXCQAAAAADMHGTD6AWJHPHQX; shshshfpb=BApXSf11g4vdA9_gYxQPrCodXgttcSU59BlTIP01o9xJ1MrWbd4C2; joyya=1730358595.1730358596.38.1m4stbn; __jdc=211148491; areaId=27; ipLoc-djd=27-2376-0-0; source=PC; platform=pc; __jda=211148491.17168938620941289400292.1716893862.1731411218.1731464105.11; mba_sid=17314651529868043134925135245.0; 3AB9D23F7A4B3C9B=3VM6TBS57CEX4IXYY4XBEB6RZS6FAACKPRVL5K3DFL5W3YPFN2WXLYWCWFK54X6HBGC4INUEKIIFQ4G4UFLQNIM56Y; __jdb=211148491.6.17168938620941289400292|11.1731464105"
        self.eid = "3VM6TBS57CEX4IXYY4XBEB6RZS6FAACKPRVL5K3DFL5W3YPFN2WXLYWCWFK54X6HBGC4INUEKIIFQ4G4UFLQNIM56Y"
        self._JdJrTdRiskFpInfo = "402623f2e85462d63041686a3303a73a"

        self.session.headers.update({
            'Cookie': self.cookie,
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
        })

        self.diff_time = self.time_diff()
        self.run_task = True

    def init_action(self):
        r = self.session.post(
            url="https://marathon.jd.com/seckillnew/orderService/pc/init.action",
            data={
                'sku': self.skuId,
                'num': '1',
                'isModifyAddress': 'false'
            }
        )
        return json.loads(r.text)

    def reserve_order(self):
        r = self.session.get(f"https://item-soa.jd.com/getWareBusiness?skuId={self.skuId}").json()
        self.session.get(url="https:" + r["yuyueInfo"]["url"])
        if "贵州茅台酒" in self.session.get("https://yushou.jd.com/member/qualificationList.action").text:
            print("预约成功")

    def submit_order(self, resp):
        addressList = resp["addressList"][0]
        data = {
            'skuId': self.skuId,
            'num': resp["seckillSkuVO"]["num"],
            'addressId': addressList["id"],
            'yuShou': 'true',
            'isModifyAddress': 'true',
            'name': addressList["name"],
            'provinceId': addressList["provinceId"],
            'cityId': addressList["cityId"],
            'countyId': addressList["countyId"],
            'townId': addressList["townId"],
            'addressDetail': addressList["addressDetail"],
            'mobile': addressList["mobile"],
            'mobileKey': addressList["mobileKey"],
            'email': addressList["email"],
            'postCode': addressList["postCode"],
            'invoiceTitle': resp["invoiceInfo"]["invoiceTitle"],
            'invoiceCompanyName': '',
            'invoiceContent': resp["invoiceInfo"]["invoiceContentType"],
            'invoiceTaxpayerNO': '',
            'invoiceEmail': resp["invoiceInfo"]["invoiceEmail"],
            'invoicePhone': resp["invoiceInfo"]["invoicePhone"],
            'invoicePhoneKey': resp["invoiceInfo"]["invoicePhoneKey"],
            'invoice': 'true',
            'password': '',
            'codTimeType': '3',
            'paymentType': '4',  # 在线支付
            'areaCode': addressList["areaCode"],
            'overseas': addressList["overseas"],
            'phone': addressList["phone"],
            'eid': self.eid,
            'fp': self._JdJrTdRiskFpInfo,
            'token': resp["token"],
            'pru': '',
            'provinceName': addressList["provinceName"],
            'cityName': addressList["cityName"],
            'countyName': addressList["countyName"],
            'townName': addressList["townName"]
        }
        while self.run_task:
            try:
                r = self.session.post(
                    url=f"https://marathon.jd.com/seckillnew/orderService/pc/submitOrder.action?skuId={self.skuId}",
                    data=data
                ).json()
                print(r)
                if r.get("success"):
                    print("=" * 39)
                    print("抢购成功！！！")
                    self.run_task = False
                    return
            except KeyboardInterrupt:
                self.run_task = False
                break
            except:
                pass
            # time.sleep(0.05)

    def main(self):
        print(f"和京东服务器时差为：{self.diff_time}")
        address_info = self.init_action()
        if address_info.get("islogin") == "-1":
            print("需要登录")
            return
        self.reserve_order()
        t = Thread(target=self.timer)
        t.setDaemon(True)
        t.start()
        time.sleep(1)
        while self.run_task:
            buy_time = datetime.strptime(self.buy_time, "%Y-%m-%d %H:%M:%S.%f")
            buy_time_ms = int(time.mktime(buy_time.timetuple()) * 1000 + buy_time.microsecond / 1000)
            if self.get_localtime() - self.diff_time >= buy_time_ms:
                print("开始抢购...")
                self.submit_order(address_info)
            else:
                time.sleep(0.5)

    def get_jd_time(self):
        # r = requests.get("https://a.jd.com//ajax/queryServerData.html").json()
        r = requests.head("https://www.jd.com",timeout=5)
        jd_server_time = r.headers.get('Date')
        #时间转换为时间戳
        # jd_server_time = datetime.strptime(jd_server_time, "%d %b %Y %H:%M:%S GWT")
        # jd_server_time = datetime.strptime(jd_server_time, "%a, %d %b %Y %H:%M:%S GWT")
        return int(datetime.strptime(jd_server_time, '%a, %d %b %Y %H:%M:%S %Z').timestamp())

    def get_localtime(self):
        return int(time.time() * 1000)

    def time_diff(self):
        return self.get_localtime() - self.get_jd_time()

    def timer(self):
        while self.run_task:
            start_time = datetime.strptime(self.buy_time, "%Y-%m-%d %H:%M:%S.%f")
            end_time = start_time + timedelta(minutes=self.run_time)
            if end_time < datetime.now():
                print("时间到，抢购结束...")
                self.run_task = False


if __name__ == "__main__":
    mt = Maotai()
    mt.main()
